//
//  ReceiveCoinView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/5/5.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
import SDWebImage
enum PatternStyle {
    case googleStyle
    case coinStyle
    
}
class ReceiveCoinView: BaseView {
    var viewModel:GoogleViewModel?
    lazy var nameLabel: UILabel = {
        let label = BaseLabel(style: .oneStyle)
        label.font = UIFont.systemFont(ofSize: 12)
        return label
    }()
    
    lazy var selectBtn:UIButton = {
        let btn:UIButton = UIButton(frame: CGRect(x: 20, y: y, width: kSCREEN_WIDTH-40, height: 40))
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btn.setTitle(kText("我已设置并保存密钥"), for: UIControlState.normal)
        btn.setTitleColor(UIColor(hexStr:"#ffffff"), for: UIControlState.normal)
        btn.addTarget(self, action: #selector(selectBtnAction), for: UIControlEvents.touchUpInside)
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 4
        CommonBtn.createImageWithColor(color: kThemeColor, btn: btn, state: UIControlState.normal)
        CommonBtn.createImageWithColor(color: kThemeColor.withAlphaComponent(0.7), btn: btn, state:
            UIControlState.highlighted)
        return btn
    }()
    
    lazy var qrCodeImageView: UIImageView = {
        let imageView = UIImageView()
        return imageView
    }()
    
    lazy var backView: UIView = {
        let view = UIView()
        view.themeBackground = ThemeManager.ThemeColorKeys.margin
        return view
    }()
    
    lazy var addressLabel: UILabel = {
        let label = BaseLabel(style: .oneStyle)
        label.numberOfLines = 0
        label.textAlignment = NSTextAlignment.center
        label.font = UIFont.systemFont(ofSize: 14)
        return label
    }()
    
    lazy var copyBtn: UIButton = {
        let btn = UIButton()
        btn.layer.cornerRadius = 3
        btn.setTitle(kText("复制地址"), for: UIControlState.normal)
        btn.addTarget(self, action: #selector(copyBtnAction), for: UIControlEvents.touchUpInside)
        btn.layer.borderColor = UIColor(hexStr: "#4671fe").cgColor
        btn.layer.borderWidth = 0.5
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.setTitleColor(UIColor(hexStr: "#4671fe"), for: UIControlState.normal)
        return btn
    }()
    
    lazy var titleLabel: UILabel = {
        let label = BaseLabel(style: .thirdStyle)
        label.font = UIFont.systemFont(ofSize: 12)
        label.numberOfLines = 0
        label.textAlignment = NSTextAlignment.center
        return label
    }()
    
    override func setUpUI()  {
        self.themeBackground = ThemeManager.ThemeColorKeys.background
        self.viewModel = dataSource as? GoogleViewModel
        
        self.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(40)
        }
        
        self.addSubview(qrCodeImageView)
        
        self.addSubview(backView)
        backView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.top.equalTo(qrCodeImageView.snp.bottom).offset(40)
            make.height.equalTo(127)
        }
        
        backView.addSubview(addressLabel)
        addressLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(35)
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
        }
        
        backView.addSubview(copyBtn)
        copyBtn.snp.makeConstraints { (make) in
            make.top.equalTo(addressLabel.snp.bottom).offset(10)
            make.centerX.equalToSuperview()
            make.height.equalTo(35)
            make.width.equalTo(130)
        }
        
        self.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.top.equalTo(backView.snp.bottom).offset(30)
            make.height.lessThanOrEqualTo(35)
        }
        
        if (viewModel?.googleBool)! {
            nameLabel.isHidden = true
            titleLabel.text = kText("请将上方的16位密钥保存在安全地方,遗失将无法恢复谷歌验证。在Authenticator上设置完成")
            qrCodeImageView.snp.makeConstraints { (make) in
               make.top.equalToSuperview().offset(20)
               make.centerX.equalToSuperview()
               make.width.height.equalTo(150)
           }
            self.addSubview(selectBtn)
            selectBtn.snp.makeConstraints { (make) in
                make.top.equalTo(titleLabel.snp.bottom).offset(20)
                make.left.equalToSuperview().offset(20)
                make.right.equalToSuperview().offset(-20)
                make.height.equalTo(40)
                
            }

        }else {
            viewModel?.addObserver(self, forKeyPath: "refreshBool", options: [.new,.old], context: nil)
            qrCodeImageView.snp.makeConstraints { (make) in
                make.top.equalToSuperview().offset(80)
                make.centerX.equalToSuperview()
                make.width.height.equalTo(150)
            }
            
            titleLabel.text = kText("请确保向该地址发送的是 比特币(BTC)，否则资产将会丢失且无法找回。")
        }
        
        
    }
    
    /// KVO监听属性
    ///
    /// - Parameters:
    ///   - keyPath: 被监听的属性名
    ///   - object:
    ///   - change:
    ///   - context:
    @objc override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "refreshBool" {
            addressLabel.text = viewModel?.receiveModel.rechargeAdd?.count != 0 ? viewModel?.receiveModel.rechargeAdd : ""
            if viewModel?.receiveModel.rechargeAdd?.count == 0 {
                qrCodeImageView.image = nil
            }else {
            qrCodeImageView.image = self.createQRForString(qrString: addressLabel.text, qrImageName: "")
            }
        }
        
    }
    
   public func setUpData()  {
    qrCodeImageView.image = self.createQRForString(qrString: (viewModel?.googleModel?.googleUrl)!, qrImageName: "")
    addressLabel.text = viewModel?.googleModel?.googleKey
    }
    
    func createQRForString(qrString: String?, qrImageName: String?) -> UIImage?{
        if let sureQRString = qrString{
            let stringData = sureQRString.data(using: String.Encoding.utf8, allowLossyConversion: false)
            //创建一个二维码的滤镜
            let qrFilter = CIFilter(name: "CIQRCodeGenerator")
            qrFilter?.setValue(stringData, forKey: "inputMessage")
            qrFilter?.setValue("H", forKey: "inputCorrectionLevel")
            let qrCIImage = qrFilter?.outputImage
            
            // 创建一个颜色滤镜,黑白色
            let colorFilter = CIFilter(name: "CIFalseColor")!
            colorFilter.setDefaults()
            colorFilter.setValue(qrCIImage, forKey: "inputImage")
            colorFilter.setValue(CIColor(red: 0, green: 0, blue: 0), forKey: "inputColor0")
            colorFilter.setValue(CIColor(red: 1, green: 1, blue: 1), forKey: "inputColor1")
            // 返回二维码image
            let codeImage = UIImage(ciImage: (colorFilter.outputImage!.transformed(by: CGAffineTransform(scaleX: 4, y: 4))))
            
            // 中间一般放logo
            if let iconImage = UIImage(named: qrImageName!) {
                let rect = CGRect(x: 0, y: 0, width: codeImage.size.width, height: codeImage.size.height)
                
                UIGraphicsBeginImageContext(rect.size)
                codeImage.draw(in: rect)
                let avatarSize = CGSize(width: rect.size.width*0.25, height: rect.size.height*0.25)
                
                let x = (rect.width - avatarSize.width) * 0.5
                let y = (rect.height - avatarSize.height) * 0.5
                iconImage.draw(in: CGRect(x: x, y: y, width: avatarSize.width, height: avatarSize.height))
                
                let resultImage = UIGraphicsGetImageFromCurrentImageContext()
                
                UIGraphicsEndImageContext()
                return resultImage
            }
            return codeImage
        }
        return nil
    }

    @objc func selectBtnAction() {
        let controller = GoogleCertificationViewController()
        controller.viewModel?.model = viewModel?.model
        controller.viewModel?.googleKey = viewModel?.googleModel?.googleKey != nil ? (viewModel?.googleModel?.googleKey)! : ""
        viewModel?.controller?.navigationController?.pushViewController(controller, animated: true)
    }
    
    @objc func copyBtnAction() {
        if addressLabel.text == nil || addressLabel.text?.count == 0 {
            CYMBShow.showMessage(kText("地址不存在"))
            return
        }
        let pastboard = UIPasteboard.general
        pastboard.string = addressLabel.text
        CYMBShow.showMessage(kText("复制地址成功"))
        
    }
    deinit {
        if !(viewModel?.googleBool)! {
        self.viewModel?.removeObserver(self, forKeyPath: "refreshBool", context: nil)
        }
    }

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
